package sk.gtug.hackatlon.drunkdroid;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.WindowManager;

/**
 * @author Richard Mihalovič
 */
public class Activity1Game extends Activity implements SensorEventListener {
    private float[] accelerometerValues = new float[3];
    private SensorManager sensorManager;
    private Activity1Canvas myCanvas;

    private Handler handler = new Handler();
    private Long startTime = 0L;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen1game);

        getWindow().setFlags(
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
        );

        Bundle bundle = this.getIntent().getExtras();
        String gameMode = bundle.getString("mode");

        myCanvas = (Activity1Canvas) findViewById(R.id.myCanvas);
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

        if(gameMode.equalsIgnoreCase("easy")) {
            myCanvas.setGameSpeedEasy();
        } else if(gameMode.equalsIgnoreCase("normal")) {
            myCanvas.setGameSpeedNormal();
        } else if(gameMode.equalsIgnoreCase("hard")) {
            myCanvas.setGameSpeedHard();
        }

        setupTimer();
    }

    private void setupTimer(){
        if (startTime == 0L) {
            startTime = System.currentTimeMillis();
            handler.removeCallbacks(updateTimerTask);
            handler.postDelayed(updateTimerTask, 50);
        }
    }

    private Runnable updateTimerTask = new Runnable() {
        public void run() {
            myCanvas.updatePosition((int) -accelerometerValues[0], (int) accelerometerValues[1]);
            myCanvas.invalidate();


            handler.postAtTime(this, SystemClock.uptimeMillis() + 50);
        }
    };

    @Override
    protected void onResume(){
        super.onResume();

        sensorManager.registerListener(
            this,
            sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
            SensorManager.SENSOR_DELAY_GAME
        );
    }

    @Override
    protected void onPause(){
        super.onPause();

        sensorManager.unregisterListener(this);
    }


    public void onSensorChanged(SensorEvent event) {
        switch (event.sensor.getType()) {
            case Sensor.TYPE_ACCELEROMETER:
                accelerometerValues = event.values.clone();
                break;
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {
    }
}
